#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
挂机参数与角色属性对应关系分析脚本
分析挂机收益计算是否与角色属性正确匹配
"""

import sqlite3
import json
from database.database_manager import DatabaseManager

def analyze_idle_parameters():
    """分析挂机参数与角色属性的对应关系"""
    print("=== 挂机参数与角色属性对应关系分析 ===")
    
    db_manager = DatabaseManager()
    
    try:
        # 1. 获取挂机地点信息
        print("\n1. 挂机地点参数分析...")
        locations_query = """
        SELECT id, name, description, min_level, max_level, base_exp_rate
        FROM idle_locations
        ORDER BY min_level
        """
        locations = db_manager.execute_query(locations_query)
        
        print(f"   共有 {len(locations)} 个挂机地点:")
        for loc in locations:
            print(f"   - {loc['name']} (ID:{loc['id']}): 等级{loc['min_level']}-{loc['max_level'] or '∞'}, 经验倍率{loc['base_exp_rate']}")
        
        # 2. 获取角色信息
        print("\n2. 角色属性分析...")
        characters_query = """
        SELECT c.id, c.name, c.character_class, c.level, c.exp, c.attack, c.defense, c.hp, c.mp, c.speed
        FROM characters c
        JOIN accounts a ON c.account_id = a.id
        WHERE a.username = 'test'
        """
        characters = db_manager.execute_query(characters_query)
        
        print(f"   test用户共有 {len(characters)} 个角色:")
        for char in characters:
            print(f"   - {char['name']} (ID:{char['id']}): {char['character_class']} Lv.{char['level']}")
            print(f"     属性: 攻击{char['attack']}, 防御{char['defense']}, 生命{char['hp']}, 魔法{char['mp']}, 速度{char['speed']}")
        
        # 3. 分析挂机记录
        print("\n3. 挂机记录分析...")
        idle_records_query = """
        SELECT ir.character_id, c.name, ir.location_id, il.name as location_name,
               ir.start_time, ir.end_time, ir.exp_gained, ir.status,
               CASE WHEN ir.status = 'active' THEN 1 ELSE 0 END as is_active
        FROM idle_records ir
        JOIN characters c ON ir.character_id = c.id
        JOIN idle_locations il ON ir.location_id = il.id
        JOIN accounts a ON c.account_id = a.id
        WHERE a.username = 'test'
        ORDER BY ir.start_time DESC
        LIMIT 10
        """
        idle_records = db_manager.execute_query(idle_records_query)
        
        print(f"   最近 {len(idle_records)} 条挂机记录:")
        for record in idle_records:
            status = "进行中" if record['is_active'] else "已结束"
            print(f"   - {record['name']} 在 {record['location_name']} 挂机 ({status})")
            print(f"     状态: {record['status']}, 收益: 经验+{record['exp_gained']}")
        
        # 4. 分析收益计算逻辑
        print("\n4. 收益计算逻辑分析...")
        
        # 查看挂机管理器的收益计算代码
        try:
            with open('src/idle/mysql_idle_manager.py', 'r', encoding='utf-8') as f:
                idle_manager_code = f.read()
                
            # 查找收益计算相关的函数
            if 'calculate_rewards' in idle_manager_code:
                print("   ✅ 找到收益计算函数")
            else:
                print("   ❌ 未找到收益计算函数")
                
            # 分析是否使用了角色属性
            attribute_usage = {
                'attack': 'attack' in idle_manager_code,
                'defense': 'defense' in idle_manager_code,
                'hp': 'hp' in idle_manager_code,
                'mp': 'mp' in idle_manager_code,
                'speed': 'speed' in idle_manager_code,
                'level': 'level' in idle_manager_code
            }
            
            print("   角色属性在挂机系统中的使用情况:")
            for attr, used in attribute_usage.items():
                status = "✅ 已使用" if used else "❌ 未使用"
                print(f"     {attr}: {status}")
                
        except FileNotFoundError:
            print("   ❌ 无法找到挂机管理器文件")
        
        # 5. 检查收益公式的合理性
        print("\n5. 收益公式合理性检查...")
        
        # 基于现有数据分析收益是否合理
        if idle_records:
            print("   基于实际挂机记录分析:")
            for record in idle_records[:3]:  # 分析前3条记录
                char_id = record['character_id']
                exp_gained = record['exp_gained']
                location_id = record['location_id']
                
                # 获取对应角色和地点信息
                char_info = next((c for c in characters if c['id'] == char_id), None)
                loc_info = next((l for l in locations if l['id'] == location_id), None)
                
                if char_info and loc_info:
                    char_level = char_info['level']
                    base_exp_rate = float(loc_info['base_exp_rate'])
                    
                    print(f"   - {char_info['name']} (Lv.{char_level}) 在 {loc_info['name']} (倍率{base_exp_rate})")
                    print(f"     实际收益: 经验{exp_gained}")
                    
                    # 简单的收益合理性检查
                    expected_base_exp = char_level * 10  # 假设基础经验
                    expected_exp = expected_base_exp * base_exp_rate
                    
                    if exp_gained > 0:
                        efficiency = exp_gained / expected_exp if expected_exp > 0 else 0
                        print(f"     预期经验: {expected_exp:.1f}, 效率: {efficiency:.2f}")
        
        # 6. 提出优化建议
        print("\n6. 优化建议...")
        
        suggestions = []
        
        # 检查是否所有角色属性都被使用
        unused_attributes = [attr for attr, used in attribute_usage.items() if not used]
        if unused_attributes:
            suggestions.append(f"考虑在收益计算中使用未利用的属性: {', '.join(unused_attributes)}")
        
        # 检查等级差异是否合理
        if characters:
            levels = [c['level'] for c in characters]
            if len(set(levels)) == 1:  # 所有角色等级相同
                suggestions.append("所有角色等级相同，建议测试不同等级角色的收益差异")
        
        # 检查挂机地点的等级要求是否合理
        if locations:
            level_gaps = []
            for i in range(len(locations) - 1):
                current_max = locations[i]['max_level'] or 999
                next_min = locations[i + 1]['min_level']
                if next_min > current_max + 1:
                    level_gaps.append((current_max + 1, next_min - 1))
            
            if level_gaps:
                suggestions.append(f"发现等级空档: {level_gaps}，建议添加对应等级的挂机地点")
        
        if suggestions:
            for i, suggestion in enumerate(suggestions, 1):
                print(f"   {i}. {suggestion}")
        else:
            print("   ✅ 当前配置看起来合理")
        
        print("\n=== 分析完成 ===")
        
    except Exception as e:
        print(f"❌ 分析过程中发生错误: {e}")
        import traceback
        traceback.print_exc()
    finally:
        # DatabaseManager使用连接池，不需要手动关闭
        pass

if __name__ == "__main__":
    analyze_idle_parameters()